from ast import parse
from datetime import datetime


def convert_to_dict(obj):
    if obj is None:
        return None
    # 如果是列表，递归转换其中的每个对象
    if isinstance(obj, list):
        return [convert_to_dict(item) for item in obj]
    # 如果是字典，递归转换字典中的每个键值对
    elif isinstance(obj, dict):
        return {key: convert_to_dict(value) for key, value in obj.items()}
    # 如果是类的实例，提取__dict__并递归转换
    elif hasattr(obj, '__dict__'):
        return {key: convert_to_dict(value) for key, value in vars(obj).items()}
    # 其他类型，例如基本数据类型，直接返回其值
    else:
        return obj


def dict_to_object(d, cls):
    """递归地将字典转换为指定类的实例"""
    if not isinstance(d, dict):
        return d
    field_types = cls.__annotations__
    new_d = {}
    for key, value in d.items():
        if key in field_types:
            field_type = field_types[key]
            if hasattr(field_type, "__origin__") and field_type.__origin__ is list:
                # 处理列表类型
                element_type = field_type.__args__[0]
                new_d[key] = [dict_to_object(item, element_type) for item in value]
            elif hasattr(field_type, "__annotations__"):
                # 处理嵌套对象
                new_d[key] = dict_to_object(value, field_type)
            else:
                if field_type == datetime and isinstance(value, str):
                    # 将字符串解析为 datetime 对象
                    new_d[key] = parse(value)
                else:
                    new_d[key] = value
        else:
            new_d[key] = value
    return cls(**new_d)
